<template>
  <div class="checkout">
    <div class="container">
      <xtx-bread>
        <xtx-bread-item to="/">首页</xtx-bread-item>
        <xtx-bread-item to="/cart">购物车</xtx-bread-item>
        <xtx-bread-item>填写订单</xtx-bread-item>
      </xtx-bread>
      <div class="wrapper" v-if="checkoutInfo">
        <!-- 收货地址 -->
        <h3 class="box-title">收货地址</h3>
        <div class="box-body">
          <!-- 收货地址组件 -->
          <checkoutAddress
            @change="changeAddress"
            :list="checkoutInfo.userAddresses"
            ref="addressEditCom"
          />
        </div>

        <!-- 商品信息 -->
        <h3 class="box-title">商品信息</h3>
        <div class="box-body">
          <table class="goods">
            <thead>
              <tr>
                <th width="520">商品信息</th>
                <th width="170">单价</th>
                <th width="170">数量</th>
                <th width="170">总价</th>
                <th width="170">实付</th>
              </tr>
            </thead>
            <tbody v-for="item in checkoutInfo.goods" :key="item.id">
              <tr>
                <td>
                  <a href="javascript:;" class="info">
                    <img :src="item.picture" alt="" />
                    <div class="right">
                      <p>{{ item.name }}</p>
                      <p>{{ item.attrsText }}</p>
                    </div>
                  </a>
                </td>
                <td>&yen;{{ item.payPrice }}</td>
                <td>{{ item.count }}</td>
                <td>&yen;{{ item.totalPrice }}</td>
                <td>&yen;{{ item.totalPayPrice }}</td>
              </tr>
            </tbody>
          </table>
        </div>

        <!-- 配送时间 -->
        <h3 class="box-title">配送时间</h3>
        <div class="box-body">
          <a
            href="javascript:;"
            @click="btnClick(1)"
            class="body_btn"
            :class="{ active: activeIndex === 1 }"
            >不限送货时间：周一至周日</a
          >
          <a
            href="javascript:;"
            class="body_btn"
            @click="btnClick(2)"
            :class="{ active: activeIndex === 2 }"
            >工作日送货：周一至周五</a
          >
          <a
            href="javascript:;"
            class="body_btn"
            @click="btnClick(3)"
            :class="{ active: activeIndex === 3 }"
            >双休日、假日送货：周六至周日</a
          >
        </div>
        <!-- 支付方式 -->
        <h3 class="box-title">支付方式</h3>
        <div class="box-body">
          <a
            href="javascript:;"
            class="body_btn"
            @click="payBtnClick(1)"
            :class="{ active: payactiveIndex === 1 }"
            >在线支付</a
          >
          <a
            href="javascript:;"
            class="body_btn"
            @click="payBtnClick(2)"
            :class="{ active: payactiveIndex === 2 }"
            >货到付款</a
          >

          <span style="color: #999">货到付款需付5元手续费</span>
        </div>
        <!-- 金额明细 -->
        <h3 class="box-title">金额明细</h3>
        <div class="box-body">
          <div class="total">
            <dl>
              <dt>商品件数：</dt>
              <dd>{{ checkoutInfo.summary.goodsCount }}</dd>
            </dl>
            <dl>
              <dt>商品总价：</dt>
              <dd>¥{{ checkoutInfo.summary.totalPrice }}</dd>
            </dl>
            <dl>
              <dt>运 <i></i> 费：</dt>
              <dd>¥{{ checkoutInfo.summary.postFee }}</dd>
            </dl>
            <dl>
              <dt>应付金额：</dt>
              <dd class="price">¥{{ checkoutInfo.summary.totalPayPrice }}</dd>
            </dl>
          </div>
        </div>
        <!-- 提交订单 -->
        <!--  -->
        <div class="submit">
          <xtx-button @click="submitCheckInfoFn" type="primary"
            >提交订单</xtx-button
          >
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { reactive, ref } from 'vue'
import checkoutAddress from './components/checkout-address'
import { createOrder, submitCheckInfo, findOrderRepurchase } from '@/api/order'
import { message } from '@/components/library/message'
import { useRouter, useRoute } from 'vue-router'
import { useStore } from 'vuex'
export default {
  name: 'Checkout',
  components: { checkoutAddress },
  setup() {
    const store = useStore()
    // 配送时间和支付方式按钮切换
    const activeIndex = ref(1)
    const payactiveIndex = ref(1)
    const checkoutInfo = ref(null)
    const addressEditCom = ref()
    const btnClick = (btnIndex) => {
      activeIndex.value = btnIndex
    }
    const payBtnClick = (btnIndex) => {
      payactiveIndex.value = btnIndex
    }
    //  结算功能-生成订单-订单信息
    const route = useRoute()
    if (route.query.orderId) {
      // 再次购买结算
      findOrderRepurchase(route.query.orderId).then((data) => {
        checkoutInfo.value = data.result
        // 设置订单商品数据
        reqParams.goods = data.result.goods.map(({ skuId, count }) => ({
          skuId,
          count
        }))
      })
    } else {
      // 购物车结算
      createOrder().then(({ result }) => {
        checkoutInfo.value = result
        // 设置提交时候的商品集合参数
        reqParams.goods = result.goods.map(({ skuId, count }) => ({
          skuId,
          count
        }))
      })
    }
    // 接收收货地址ID
    const changeAddress = (id) => {
      reqParams.addressId = id
    }
    // 需要提交的字段（获取地址id）
    const reqParams = reactive({
      deliveryTimeType: 1,
      payType: 1,
      payChannel: 1,
      buyerMessage: '',
      //  商品信息，获取订单信息后设置
      goods: [],
      // 收货地址，切换收货地址或者组件默认的时候设置
      addressId: null
    })
    const router = useRouter()
    // 提交订单
    const submitCheckInfoFn = () => {
      console.log(reqParams.addressId, 'addressId')
      // 检查收货地址是否选好
      if (!reqParams.addressId) {
        return message({ message: '亲，请选择收货地址', type: 'warn' })
      }

      submitCheckInfo(reqParams).then((data) => {
        // 清理本地购物车
        store.dispatch('cart/findCartList')
        // 提交订单成功
        message({ type: 'success', message: '提交订单成功' })
        // 跳转支付页面
        router.push(`/member/pay?orderId=${data.result.id}`)
      })
      // const { result } = submitCheckInfo(reqParams)
      // // 提示
      // message({ type: 'success', message: '提交订单成功' })
      // // 跳转
      // // router.push({
      // //   path: '/member/pay',
      // //   query: { orderId: result.id, payResult: result.orderState }
      // // })
      // // 跳转支付页面
      // router.push(`/member/pay?orderId=${result.id}`)
      // // 清理本地购物车
      // store.dispatch('cart/findCartList')
    }

    return {
      activeIndex,
      payactiveIndex,
      btnClick,
      payBtnClick,
      checkoutInfo,
      reqParams,
      changeAddress,
      addressEditCom,
      submitCheckInfoFn
    }
  }
}
</script>
<style scoped lang="less">
.checkout {
  min-height: 600px;
  .wrapper {
    background-color: #fff;
    padding: 0 20px;
    margin: 0 0 20px 0;
    h3 {
      padding: 25px 10px;
      font-size: 16px;
      font-weight: normal;
      border-bottom: 1px solid #eee;
    }
    .box-body {
      padding: 20px 0;

      .goods {
        width: 100%;
        border-collapse: collapse;
        border-spacing: 0;
        .info {
          display: flex;
          text-align: left;
          img {
            width: 70px;
            height: 70px;
            margin-right: 20px;
          }
          .right {
            line-height: 24px;
            p {
              &:last-child {
                color: #999;
              }
            }
          }
        }
        tr {
          th {
            background-color: #f5f5f5;
            font-size: 14px;
            font-weight: normal;
          }
          td,
          th {
            padding: 20px;
            text-align: center;
            border-bottom: 1px solid #f5f5f5;
            &:first-child {
              border-left: 1px solid #f5f5f5;
            }
            &:last-child {
              border-right: 1px solid #f5f5f5;
            }
          }
        }
      }
      .body_btn {
        width: 228px;
        height: 50px;
        line-height: 48px;
        border: 1px solid #e4e4e4;
        text-align: center;
        margin-right: 25px;
        color: #666666;
        display: inline-block;
        &.active,
        &:hover {
          border-color: @color;
        }
      }
      .total {
        dl {
          display: flex;
          justify-content: flex-end;
          line-height: 50px;
          dt {
            i {
              display: inline-block;
              width: 1.3em;
            }
          }
          dd {
            width: 240px;
            text-align: right;
            padding-right: 70px;
            &.price {
              font-size: 20px;
              color: @priceColor;
            }
          }
        }
      }
    }
    .submit {
      text-align: right;
      padding: 60px;
      border-top: 1px solid #f5f5f5;
    }
  }
  .loading {
    width: 1240px;
    min-height: 600px;
    background-color: #fff !important;
    margin: 70px auto 45px auto;
    background: url(~@/assets/images/loading.gif) no-repeat center;
  }
}
</style>
